// import VueRouter from  'vue-router';// vue2 导入方式

// vue3 函数式编程
import { createRouter, createWebHashHistory } from "vue-router";
import { useUserStore } from "../stores/useUserStore.js";

// 路由映射表（定义 path 和 component 的关系）
const routes = [
  {
    path: "/", // 浏览器默认的行为，默认会在 /
    redirect: "/home",
  },
  {
    path: "/home",
    name: "home",
    component: () => import("../pages/Home/index.vue"),
  },
  {
    path: "/company",
    name: "company",
    component: () => import("../pages/Company/index.vue"),
  },
  {
    path: "/message",
    name: "message",
    component: () => import("../pages/Message/index.vue"),
    meta: { requiresAuth: true }, // 需要登录的页面
  },
  {
    path: "/mine",
    name: "mine",
    component: () => import("../pages/Mine/index.vue"),
    meta: { requiresAuth: true }, // 需要登录的页面
  },
  {
    path: "/login",
    name: "login",
    component: () => import("../pages/Login.vue"),
  },
  {
    path: "/workdetail/:id",
    name: "work_detail",
    component: () => import("../pages/Work/Detail.vue"),
  },
  {
    path: "/companydetail/:id",
    name: "company_detail",
    component: () => import("../pages/Company/detail.vue"),
  },
  {
    path: "/chat/:id",
    name: "chat",
    component: () => import("../pages/Message/chat.vue"),
  },
];
const router = createRouter({
  // mode  vue2 设置路由的模式
  // vue3 设置路由的模式
  history: createWebHashHistory(),
  routes,
});

// 全局前置守卫
router.beforeEach((to, from, next) => {
  const userStore = useUserStore(); // 获取用户状态

  // 检查路由是否需要登录权限
  if (to.meta.requiresAuth && !userStore.token) {
    next({
      path: "/login",
      query: { redirect: to.fullPath }, // 保存跳转前的路径，用于登录后返回
    });
  } else {
    next(); // 允许通行
  }
});
export default router;
